package review.test1.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import review.dao.Test1DAO;
import review.entity.Test1;

import java.util.Optional;

@Service
@Transactional
public class Test1ServiceImpl implements Test1Service {
	@Autowired
	private Test1DAO test1DAO;

	public void addTest1(Test1 test1) {

    if (!StringUtils.hasText(test1.getName())) {
			throw new RuntimeException("姓名不能为空！");
		}
    if (test1.getAge() == null) {
			throw new RuntimeException("年龄不能为空！");
		}
		
		test1DAO.save(test1);
		
	}

	// 删除
	public void deleteTest1s(Integer[] ids) {
		if (ids.length == 0) {
			throw new RuntimeException("未选择删除对象");
		}
		for (Integer id : ids) {
			if (test1DAO.existsById(id)) {
				test1DAO.deleteById(id);
			} else {
				throw new RuntimeException(String.format("ID为：%d的记录未找到", id));
			}
		}
	}

	// 修改
	public void updateTest1(Test1 test1) {
		Optional<Test1> o = test1DAO.findById(test1.getId());
		if (!o.isPresent()) {
			throw new RuntimeException("ID不存在");
		}
		//唯一性判断
    /*
    * 
    */
		test1DAO.save(test1);
	}

	// 分页模糊查询
	public Page<Test1> findAll(int page, int size, Test1 test1) {
		ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreNullValues()
    .withMatcher("sex",ExampleMatcher.GenericPropertyMatchers.contains())
    .withMatcher("name",ExampleMatcher.GenericPropertyMatchers.contains())
    ;
		Example<Test1> example = Example.of(test1, matcher);
		Pageable pageable = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.ASC, "id"));
		return test1DAO.findAll(example, pageable);
	}
}
